package com.invest.config;

import com.invest.service.UserService;
import com.invest.utils.security.PasswordUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

/**
 * <p>注释</p>
 *
 * @author yuyizhao
 * @version v0.1 2016/3/10 Exp
 */
@Service
public class DbAuthenticationProvider implements AuthenticationProvider {
    private static final Logger LOGGER = LoggerFactory.getLogger(DbAuthenticationProvider.class);
    @Autowired
    private UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        //查询
        UserDetails details = userService.loadUserByUsername(username);

        //校验
        validatePwd(details,password);

        //保存凭证
        return  new UsernamePasswordAuthenticationToken(details,null, details.getAuthorities());

    }

    private void validatePwd( UserDetails details,String password){
        if(details == null){
            LOGGER.error(details.getUsername()+"用户不存在");
            throw new BadCredentialsException("用户不存在");
        }
        String encodePwd  = PasswordUtils.md5Pwd(details.getUsername(),password);
        if(!StringUtils.equals(details.getPassword(),encodePwd) && !StringUtils.equals(details.getPassword(),password)){
            LOGGER.error(details.getUsername()+"用户名或密码不正确");
            throw new BadCredentialsException("用户名或密码不正确");
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
